package com.cert;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.util.Arrays;
import java.util.List;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class TestSSL  {
	private static String url = null;
	private static String keyStorePath = null;
	private static String keyStorepasswd = null;
	private static String trustStorePath = null;
	private static String trustStopasswd = null;
	private static int port = 0;

	public static void main(String[] args) throws Exception {
		send();
		
		// System.out.println(new SimpleDateFormat("hhmmssSSS").format(new
		// Date())+ String.format("%03d", 3));
		// System.out.println("tRue".toString().toLowerCase());
	} 	

	public static String send() throws IOException {
//		keyStorePath = "E:\\baoql\\jks\\ip_pay_key.jks";
//		keyStorePath = "E:\\baoql\\jks\\xpay_key.jks";
		
		keyStorePath = "E:\\JAVA\\project\\SmartESB\\https_ssl\\apple_pay\\test.jks"; // test
		
		keyStorepasswd = "123456";
		trustStorePath =keyStorePath;// "F:\\data\\ca\\xpay_key.jks";
		trustStopasswd = "123456";
//		url = "https://128.160.12.234:4002/huaweiPay/services";
		url = "https://web.cupdata.com/weixin/ajax/getJSSDKConfig.do";
//		https://127.0.0.1:4002/huaweiPay/services
//		url="https://128.160.12.234:4001/applePay/services";
//		url="https://128.160.12.176:4001/applePay/services";
		String returnMsg = null;
		String reqStr = "";
		try {
			
			 reqStr = datetransxml("service_Defaultcd_system_default.xml");//1003-t003-0400200000202触发动态验证请求
			 reqStr = "{\"bankNum\":\"6443\",\"url\":\"http://www.bankgy.cn\"}";
			//applepay测试数据 begin
//			 reqStr = datetransxml("req_apple_t005.xml");//1007-t005-0400200000204 移动设备卡映射关系状态变更通知（银联发起）
			 //applepay测试数据	 end
			 
		} catch (DocumentException e1) {
			e1.printStackTrace();
		}

		System.out.println("请求报文为[" + reqStr + "]");

		try {
			KeyStore keyStore = KeyStore.getInstance("jks");
			KeyStore trustStore = KeyStore.getInstance("jks");
			InputStream ksIn = new FileInputStream(keyStorePath);
			InputStream tsIn = new FileInputStream(trustStorePath);
			try {
				keyStore.load(ksIn, keyStorepasswd.toCharArray());
				trustStore.load(tsIn, trustStopasswd.toCharArray());
			} finally {
				try {
					ksIn.close();
				} catch (Exception localException1) {
				}
				try {
					tsIn.close();
				} catch (Exception localException2) {
				}
			}
			KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
			kmf.init(keyStore, keyStorepasswd.toCharArray());

			TrustManagerFactory tmf = TrustManagerFactory
					.getInstance("SunX509");
			tmf.init(trustStore);
			SSLContext sslcontext = SSLContext.getInstance("TLSv1");
			sslcontext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
					sslcontext, new String[] { "TLSv1" }, null,
					SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

			CloseableHttpClient httpclient = HttpClients.custom()
					.setSSLSocketFactory(sslsf).build();
			HttpPost httppost = new HttpPost(url);
//			httppost.addHeader("Connection", "close");//开启后，服务端会发起RST
			StringEntity reqEntity = new StringEntity(reqStr);
	//		reqEntity.setContentType("application/soap+xml");
			reqEntity.setContentType("application/json");
			
			httppost.setEntity(reqEntity);
			CloseableHttpResponse response = httpclient.execute(httppost);
			Header[] allHeaders = response.getAllHeaders();
			System.out.println(Arrays.toString(allHeaders));
			HttpEntity entity2 = response.getEntity();
			InputStream in = entity2.getContent();
			
			byte [] buff = new byte[1024];			
			int total = 0;
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			while (total != -1) {
				total = in.read(buff, 0, buff.length);
				bout.write(buff);
			}
			String string = new String(bout.toByteArray());
			System.out.println(string);
			
			System.out.print("获取响应报文:"+new String(bout.toByteArray(),"utf-8"));
			returnMsg = new String(buff,"utf-8");
			response.close();//若无此句，将使用java自动回收机制
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("SSL认证异常:" + e.getMessage());
		}
		return returnMsg;
	}

	private static String datetransxml(String filename)
			throws DocumentException {
		SAXReader reader = new SAXReader();
		Document doc = reader.read(new File("E:\\JAVA\\project\\SmartESB/configs/in_conf/metadata/ERROR/" + filename));
		List<Element> nodes = doc.getRootElement().elements();
		for (Element nodet : nodes) {
			int i = nodet.attributeCount();
			for (int j = 0; j < i; j++) {
				String attvalue = nodet.attribute(j).getText();
				nodet.attribute(j).setText(attvalue);
			}
		}
		return doc.asXML().toString();
	}

	public  String filedata(String filename)
			throws DocumentException {
		SAXReader reader = new SAXReader();
		Document doc = reader.read(new File(filename));		 
		return doc.asXML().toString();
	}
	
 
}